const db = require('../config/db.config.js');

// 获取课程列表（带报名状态）
exports.getCoursesWithRegistration = async (req, res) => {
  try {
    const userId = req.user.id;
    const [courses] = await db.query(
      `SELECT c.*, 
        CASE WHEN uc.user_id IS NOT NULL THEN true ELSE false END as isRegistered
      FROM Courses c
      LEFT JOIN User_Courses uc ON c.id = uc.course_id AND uc.user_id = ?
      ORDER BY c.schedule DESC`,
      [userId]
    );
    res.json(courses);
  } catch (error) {
    console.error('获取课程列表失败:', error);
    res.status(500).json({ message: '获取课程列表失败' });
  }
};

// 获取课程列表
exports.getAllCourses = async (req, res) => {
  try {
    const [courses] = await db.query('SELECT * FROM Courses');
    res.json(courses);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 添加新课程(管理员)
exports.addCourse = async (req, res) => {
  try {
    const { title, description, teacher, schedule, video_path } = req.body;
    console.log('接收到的课程数据:', {
      title,
      description,
      teacher,
      schedule,
      video_path,
    });

    const videoUrl = video_path
      ? JSON.stringify([`/uploads/courses/videos/${video_path}`])
      : null;
    console.log('构建的视频URL:', videoUrl);

    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '无权限执行此操作' });
    }

    const [result] = await db.query(
      'INSERT INTO Courses (title, description, teacher, schedule, video_url, likes_count, favorites_count) VALUES (?, ?, ?, ?, ?, 0, 0)',
      [title, description, teacher, schedule, videoUrl]
    );

    console.log('数据库插入结果:', result);

    // 更新share_url
    await db.query('UPDATE Courses SET share_url = ? WHERE id = ?', [
      `http://localhost:5174/courses/${result.insertId}`, // 修改这里
      result.insertId, // 修改这里
    ]);

    res.status(201).json({
      message: '课程添加成功',
      courseId: result.insertId,
      shareUrl: `http://localhost:5174/courses/${result.insertId}`,
    });
  } catch (error) {
    console.error('创建课程失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      message: '服务器错误',
      details: error.sqlMessage || error.message,
    });
  }
};

// 删除课程(管理员)
exports.deleteCourse = async (req, res) => {
  const connection = await db.getConnection();

  try {
    await connection.beginTransaction();
    const { courseId } = req.params;

    if (req.user.role !== 'admin') {
      await connection.rollback();
      return res.status(403).json({ message: '无权限执行此操作' });
    }

    // 先检查课程是否存在
    const [course] = await connection.query(
      'SELECT id FROM Courses WHERE id = ?',
      [courseId]
    );

    if (course.length === 0) {
      await connection.rollback();
      return res.status(404).json({ message: '课程不存在' });
    }

    // 先删除关联的报名记录
    console.log('正在删除课程报名记录...');
    await connection.query('DELETE FROM User_Courses WHERE course_id = ?', [
      courseId,
    ]);
    console.log('课程报名记录删除成功');

    // 再删除课程本身
    console.log('正在删除课程...');
    await connection.query('DELETE FROM Courses WHERE id = ?', [courseId]);
    console.log('课程删除成功');

    await connection.commit();
    res.json({ message: '课程删除成功' });
  } catch (error) {
    await connection.rollback();
    console.error('删除课程失败:', error);
    res.status(500).json({
      message: '删除失败',
      details: error.sqlMessage || error.message,
    });
  } finally {
    connection.release();
  }
};

// 更新课程信息(管理员)
exports.updateCourse = async (req, res) => {
  try {
    const { courseId } = req.params;
    const { title, description, teacher, schedule, video_path } = req.body;
    console.log('更新课程，接收到的数据:', {
      courseId,
      title,
      description,
      teacher,
      schedule,
      video_path,
    });

    // 构建视频URL，与创建课程时保持一致
    const videoUrl = video_path
      ? JSON.stringify([`/uploads/courses/videos/${video_path}`])
      : null;
    console.log('更新课程，构建的视频URL:', videoUrl);

    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '无权限执行此操作' });
    }

    const [result] = await db.query(
      'UPDATE Courses SET title = ?, description = ?, teacher = ?, schedule = ?, video_url = ? WHERE id = ?',
      [title, description, teacher, schedule, videoUrl, courseId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }

    res.json({
      message: '课程更新成功',
      debug: {
        videoUrl,
        affectedRows: result.affectedRows,
      },
    });
  } catch (error) {
    console.error('更新课程失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      message: '服务器错误',
      details: error.sqlMessage || error.message,
    });
  }
};

// 报名课程
exports.enrollCourse = async (req, res) => {
  try {
    const { courseId } = req.body;
    const userId = req.user.id;

    console.log('报名课程:', { courseId, userId });

    // 检查是否已经报名
    const [existing] = await db.query(
      'SELECT * FROM User_Courses WHERE user_id = ? AND course_id = ?',
      [userId, courseId]
    );

    if (existing.length > 0) {
      return res.status(400).json({ message: '已经报名过该课程' });
    }

    // 添加报名记录
    await db.query(
      'INSERT INTO User_Courses (user_id, course_id, enrolled_at) VALUES (?, ?, NOW())',
      [userId, courseId]
    );

    // 获取更新后的课程信息
    const [course] = await db.query(
      `SELECT c.*, 
        CASE WHEN uc.user_id IS NOT NULL THEN 1 ELSE 0 END as is_registered
      FROM Courses c
      LEFT JOIN User_Courses uc ON c.id = uc.course_id AND uc.user_id = ?
      WHERE c.id = ?`,
      [userId, courseId]
    );

    console.log('报名成功，更新后的课程信息:', course[0]);

    res.status(201).json({
      message: '报名成功',
      course: course[0]
    });
  } catch (error) {
    console.error('报名失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 完成课程
exports.completeCourse = async (req, res) => {
  try {
    const { courseId } = req.body;
    const userId = req.user.id;

    const [result] = await db.query(
      'UPDATE User_Courses SET completed = true WHERE user_id = ? AND course_id = ?',
      [userId, courseId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '未找到课程记录' });
    }

    res.json({ message: '课程已标记为完成' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户的课程记录
exports.getUserCourses = async (req, res) => {
  try {
    const userId = req.user.id;

    const [courses] = await db.query(
      `
      SELECT c.*, uc.enrolled_at, uc.completed
      FROM Courses c
      INNER JOIN User_Courses uc ON c.id = uc.course_id
      WHERE uc.user_id = ?
      ORDER BY c.schedule DESC
    `,
      [userId]
    );

    res.json(courses);
  } catch (error) {
    console.error('获取用户课程记录失败:', error);
    res.status(500).json({ message: '获取课程记录失败' });
  }
};

// 添加视频上传功能
exports.uploadVideo = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '请选择要上传的视频文件' });
    }

    const courseId = req.params.courseId;

    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '无权限执行此操作' });
    }

    // 检查课程是否存在
    const [course] = await db.query('SELECT id FROM Courses WHERE id = ?', [
      courseId,
    ]);
    if (!course || course.length === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }

    const videoUrl = `/uploads/videos/${req.file.filename}`;

    // 更新课程的视频URL
    const [result] = await db.query(
      'UPDATE Courses SET video_url = ? WHERE id = ?',
      [videoUrl, courseId]
    );

    if (result.affectedRows === 0) {
      return res.status(500).json({ message: '更新视频URL失败' });
    }

    res.json({
      message: '视频上传成功',
      video_url: videoUrl,
    });
  } catch (error) {
    console.error('视频上传失败:', error);
    res.status(500).json({ message: '视频上传失败' });
  }
};

// 获取课程详情（包含点赞、收藏和报名状态）
exports.getCourseDetail = async (req, res) => {
  try {
    const courseId = req.params.courseId;
    const userId = req.user?.id;

    console.log('获取课程详情:', { courseId, userId });

    let query = `
      SELECT c.*, 
        COUNT(DISTINCT l.id) as likes_count,
        COUNT(DISTINCT f.id) as favorites_count,
        MAX(CASE WHEN l2.id IS NOT NULL THEN 1 ELSE 0 END) as is_liked,
        MAX(CASE WHEN f2.id IS NOT NULL THEN 1 ELSE 0 END) as is_favorited,
        MAX(CASE WHEN uc.user_id IS NOT NULL THEN 1 ELSE 0 END) as is_registered
      FROM Courses c
      LEFT JOIN Likes l ON c.id = l.content_id AND l.content_type = 'course'
      LEFT JOIN Favorites f ON c.id = f.content_id AND f.content_type = 'course'
      LEFT JOIN Likes l2 ON c.id = l2.content_id AND l2.content_type = 'course' AND l2.user_id = ?
      LEFT JOIN Favorites f2 ON c.id = f2.content_id AND f2.content_type = 'course' AND f2.user_id = ?
      LEFT JOIN User_Courses uc ON c.id = uc.course_id AND uc.user_id = ?
      WHERE c.id = ?
      GROUP BY c.id
    `;

    const [courses] = await db.query(query, [userId, userId, userId, courseId]);

    if (courses.length === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }

    // 生成分享URL
    const shareUrl = `${process.env.FRONTEND_URL}/course/${courseId}`;
    courses[0].share_url = shareUrl;

    console.log('课程详情结果:', courses[0]);

    res.json(courses[0]);
  } catch (error) {
    console.error('获取课程详情失败:', error);
    res.status(500).json({ message: '获取课程详情失败' });
  }
};

// 点赞课程
exports.likeCourse = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const courseId = req.params.courseId;
    const userId = req.user.id;

    // 检查是否已点赞
    const [existing] = await connection.query(
      'SELECT * FROM Likes WHERE user_id = ? AND content_id = ? AND content_type = "course"',
      [userId, courseId]
    );

    if (existing.length > 0) {
      // 取消点赞
      await connection.query(
        'DELETE FROM Likes WHERE user_id = ? AND content_id = ? AND content_type = "course"',
        [userId, courseId]
      );
      await connection.query(
        'UPDATE Courses SET likes_count = likes_count - 1 WHERE id = ?',
        [courseId]
      );
      await connection.commit();
      return res.json({ message: '取消点赞成功', liked: false });
    }

    // 添加点赞
    await connection.query(
      'INSERT INTO Likes (user_id, content_id, content_type) VALUES (?, ?, "course")',
      [userId, courseId]
    );
    await connection.query(
      'UPDATE Courses SET likes_count = likes_count + 1 WHERE id = ?',
      [courseId]
    );

    await connection.commit();
    res.json({ message: '点赞成功', liked: true });
  } catch (error) {
    await connection.rollback();
    console.error('课程点赞失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};

// 收藏课程
exports.favoriteCourse = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const courseId = req.params.courseId;
    const userId = req.user.id;

    // 检查是否已收藏
    const [existing] = await connection.query(
      'SELECT * FROM Favorites WHERE user_id = ? AND content_id = ? AND content_type = "course"',
      [userId, courseId]
    );

    if (existing.length > 0) {
      // 取消收藏
      await connection.query(
        'DELETE FROM Favorites WHERE user_id = ? AND content_id = ? AND content_type = "course"',
        [userId, courseId]
      );
      await connection.query(
        'UPDATE Courses SET favorites_count = favorites_count - 1 WHERE id = ?',
        [courseId]
      );
      await connection.commit();
      return res.json({ message: '操作成功', favorited: false });
    }

    // 添加收藏
    await connection.query(
      'INSERT INTO Favorites (user_id, content_id, content_type) VALUES (?, ?, "course")',
      [userId, courseId]
    );
    await connection.query(
      'UPDATE Courses SET favorites_count = favorites_count + 1 WHERE id = ?',
      [courseId]
    );

    await connection.commit();
    res.json({ message: '操作成功', favorited: true });
  } catch (error) {
    await connection.rollback();
    console.error('课程收藏失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};
